import React, { useState, useEffect } from 'react'
import { Card, Table, Button, Tag, Space, Modal, Form, Input, Select, message, Row, Col, Avatar, Progress, Timeline } from 'antd'
import { EyeOutlined, EditOutlined, PlusOutlined, SearchOutlined, TeamOutlined, DeleteOutlined } from '@ant-design/icons'

interface ConstructionProject {
  id: string
  name: string
  type: 'infrastructure' | 'digital' | 'agricultural' | 'environmental'
  village: string
  startDate: string
  endDate: string
  progress: number
  status: 'planning' | 'in-progress' | 'completed' | 'delayed'
  description: string
  budget: number
  spent: number
  manager: string
  participants: number
  contractor: string
  milestones: Milestone[]
}

interface Milestone {
  id: string
  name: string
  date: string
  status: 'completed' | 'current' | 'upcoming'
  description: string
}

const DigitalRuralConstructionManagement: React.FC = () => {
  const [projects, setProjects] = useState<ConstructionProject[]>([])
  const [loading, setLoading] = useState(true)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingProject, setEditingProject] = useState<ConstructionProject | null>(null)
  const [searchText, setSearchText] = useState('')
  const [isMilestoneModalVisible, setIsMilestoneModalVisible] = useState(false)
  const [selectedProject, setSelectedProject] = useState<ConstructionProject | null>(null)

  // mock数据 - 与用户端DigitalRuralConstruction页面关联
  useEffect(() => {
    const mockData: ConstructionProject[] = [
      {
        id: '1',
        name: '智慧农业示范园建设',
        type: 'agricultural',
        village: '幸福村',
        startDate: '2024-01-01',
        endDate: '2024-06-30',
        progress: 65,
        status: 'in-progress',
        description: '建设现代化智慧农业示范园区，推广智能灌溉、无人机植保等技术',
        budget: 5000000,
        spent: 3250000,
        manager: '张大山',
        participants: 45,
        contractor: '绿源建设公司',
        milestones: [
          {
            id: '1',
            name: '项目启动',
            date: '2024-01-15',
            status: 'completed',
            description: '项目正式启动，完成前期准备工作'
          },
          {
            id: '2',
            name: '基础设施建设',
            date: '2024-03-01',
            status: 'current',
            description: '完成园区道路、水电等基础设施建设'
          },
          {
            id: '3',
            name: '设备安装调试',
            date: '2024-04-01',
            status: 'upcoming',
            description: '安装智能灌溉系统、监控设备等'
          }
        ]
      },
      {
        id: '2',
        name: '数字乡村网络覆盖',
        type: 'digital',
        village: '和平村',
        startDate: '2024-02-01',
        endDate: '2024-12-31',
        progress: 30,
        status: 'in-progress',
        description: '实现全村5G网络覆盖，建设数字乡村服务平台',
        budget: 3000000,
        spent: 900000,
        manager: '李小花',
        participants: 28,
        contractor: '电信工程公司',
        milestones: [
          {
            id: '1',
            name: '基站建设',
            date: '2024-02-15',
            status: 'completed',
            description: '完成5G基站基础设施建设'
          },
          {
            id: '2',
            name: '网络覆盖测试',
            date: '2024-03-15',
            status: 'current',
            description: '进行网络覆盖测试和优化'
          }
        ]
      },
      {
        id: '3',
        name: '乡村道路升级改造',
        type: 'infrastructure',
        village: '富裕村',
        startDate: '2023-11-01',
        endDate: '2024-03-31',
        progress: 95,
        status: 'completed',
        description: '升级改造村内主干道，改善交通条件',
        budget: 2000000,
        spent: 1900000,
        manager: '王老五',
        participants: 32,
        contractor: '路桥建设公司',
        milestones: [
          {
            id: '1',
            name: '道路勘测设计',
            date: '2023-11-15',
            status: 'completed',
            description: '完成道路勘测和设计方案'
          },
          {
            id: '2',
            name: '道路施工',
            date: '2024-01-10',
            status: 'completed',
            description: '完成道路主体工程施工'
          },
          {
            id: '3',
            name: '项目验收',
            date: '2024-03-01',
            status: 'completed',
            description: '完成项目验收工作'
          }
        ]
      }
    ]

    setTimeout(() => {
      setProjects(mockData)
      setLoading(false)
    }, 1000)
  }, [])

  const columns = [
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (text: string, record: ConstructionProject) => (
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.village}</div>
        </div>
      )
    },
    {
      title: '项目类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => {
        const typeMap = {
          infrastructure: { text: '基础设施', color: 'blue' },
          digital: { text: '数字建设', color: 'purple' },
          agricultural: { text: '农业项目', color: 'green' },
          environmental: { text: '环境治理', color: 'orange' }
        }
        const config = typeMap[type as keyof typeof typeMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '项目负责人',
      dataIndex: 'manager',
      key: 'manager',
      width: 120,
      render: (manager: string) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <Avatar size="small" style={{ backgroundColor: '#1890ff' }}>
            {manager.charAt(0)}
          </Avatar>
          {manager}
        </div>
      )
    },
    {
      title: '项目进度',
      key: 'progress',
      width: 150,
      render: (record: ConstructionProject) => (
        <div>
          <Progress percent={record.progress} size="small" />
          <div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
            {record.startDate} ~ {record.endDate}
          </div>
        </div>
      )
    },
    {
      title: '项目状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusMap = {
          planning: { text: '规划中', color: 'orange' },
          'in-progress': { text: '进行中', color: 'blue' },
          completed: { text: '已完成', color: 'green' },
          delayed: { text: '延期', color: 'red' }
        }
        const config = statusMap[status as keyof typeof statusMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '预算/支出',
      key: 'budget',
      width: 120,
      render: (record: ConstructionProject) => (
        <div style={{ fontSize: '12px' }}>
          <div>预算: ¥{record.budget.toLocaleString()}</div>
          <div>支出: ¥{record.spent.toLocaleString()}</div>
        </div>
      )
    },
    {
      title: '参与人数',
      dataIndex: 'participants',
      key: 'participants',
      width: 100,
      render: (participants: number) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
          <TeamOutlined style={{ color: '#52c41a' }} />
          {participants}人
        </div>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (record: ConstructionProject) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EyeOutlined />}>详情</Button>
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            size="small"
            onClick={() => handleMilestone(record)}
          >
            里程碑
          </Button>
          <Button type="link" size="small" icon={<DeleteOutlined />} danger>删除</Button>
        </Space>
      )
    }
  ]

  const handleAdd = () => {
    setEditingProject(null)
    setIsModalVisible(true)
  }

  const handleEdit = (record: ConstructionProject) => {
    setEditingProject(record)
    setIsModalVisible(true)
  }

  const handleMilestone = (record: ConstructionProject) => {
    setSelectedProject(record)
    setIsMilestoneModalVisible(true)
  }

  const handleSubmit = (values: any) => {
    if (editingProject) {
      // 编辑现有项目
      setProjects(projects.map(item => 
        item.id === editingProject.id 
          ? { ...item, ...values }
          : item
      ))
      message.success('项目信息更新成功')
    } else {
      // 添加新项目
      const newProject: ConstructionProject = {
        id: Date.now().toString(),
        name: values.name,
        type: values.type,
        village: values.village,
        startDate: values.startDate,
        endDate: values.endDate,
        progress: 0,
        status: 'planning',
        description: values.description,
        budget: values.budget,
        spent: 0,
        manager: values.manager,
        participants: 0,
        contractor: values.contractor,
        milestones: []
      }
      setProjects([newProject, ...projects])
      message.success('项目添加成功')
    }
    setIsModalVisible(false)
  }

  const filteredProjects = projects.filter(project =>
    project.name.toLowerCase().includes(searchText.toLowerCase()) ||
    project.village.toLowerCase().includes(searchText.toLowerCase()) ||
    project.manager.toLowerCase().includes(searchText.toLowerCase())
  )

  const statistics = {
    total: projects.length,
    planning: projects.filter(p => p.status === 'planning').length,
    inProgress: projects.filter(p => p.status === 'in-progress').length,
    completed: projects.filter(p => p.status === 'completed').length
  }

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card 
        title="数字乡村建设管理"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加项目
          </Button>
        }
      >
        {/* 统计信息 */}
        <Row gutter={16} style={{ marginBottom: '24px' }}>
          <Col span={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                  {statistics.total}
                </div>
                <div style={{ color: '#666' }}>总项目数</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#faad14' }}>
                  {statistics.planning}
                </div>
                <div style={{ color: '#666' }}>规划中</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
                  {statistics.inProgress}
                </div>
                <div style={{ color: '#666' }}>进行中</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#13c2c2' }}>
                  {statistics.completed}
                </div>
                <div style={{ color: '#666' }}>已完成</div>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 搜索和筛选 */}
        <Row gutter={16} style={{ marginBottom: '16px' }}>
          <Col span={8}>
            <Input
              placeholder="搜索项目名称、村庄或负责人"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={e => setSearchText(e.target.value)}
            />
          </Col>
          <Col span={8}>
            <Select placeholder="选择项目类型" style={{ width: '100%' }} allowClear>
              <Select.Option value="infrastructure">基础设施</Select.Option>
              <Select.Option value="digital">数字建设</Select.Option>
              <Select.Option value="agricultural">农业项目</Select.Option>
              <Select.Option value="environmental">环境治理</Select.Option>
            </Select>
          </Col>
          <Col span={8}>
            <Select placeholder="选择项目状态" style={{ width: '100%' }} allowClear>
              <Select.Option value="planning">规划中</Select.Option>
              <Select.Option value="in-progress">进行中</Select.Option>
              <Select.Option value="completed">已完成</Select.Option>
              <Select.Option value="delayed">延期</Select.Option>
            </Select>
          </Col>
        </Row>

        <Table
          loading={loading}
          columns={columns}
          dataSource={filteredProjects}
          rowKey="id"
          pagination={{
            total: filteredProjects.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 个项目`
          }}
        />
      </Card>

      {/* 添加/编辑弹窗 */}
      <Modal
        title={editingProject ? '编辑项目' : '添加项目'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          layout="vertical"
          initialValues={editingProject || {
            type: 'infrastructure',
            village: '幸福村',
            status: 'planning'
          }}
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="项目名称"
                name="name"
                rules={[{ required: true, message: '请输入项目名称' }]}
              >
                <Input placeholder="请输入项目名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="项目类型"
                name="type"
                rules={[{ required: true, message: '请选择项目类型' }]}
              >
                <Select placeholder="请选择项目类型">
                  <Select.Option value="infrastructure">基础设施</Select.Option>
                  <Select.Option value="digital">数字建设</Select.Option>
                  <Select.Option value="agricultural">农业项目</Select.Option>
                  <Select.Option value="environmental">环境治理</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="所属村庄"
                name="village"
                rules={[{ required: true, message: '请选择所属村庄' }]}
              >
                <Select placeholder="请选择所属村庄">
                  <Select.Option value="幸福村">幸福村</Select.Option>
                  <Select.Option value="和平村">和平村</Select.Option>
                  <Select.Option value="富裕村">富裕村</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="项目负责人"
                name="manager"
                rules={[{ required: true, message: '请输入项目负责人' }]}
              >
                <Input placeholder="请输入项目负责人" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="开始日期"
                name="startDate"
                rules={[{ required: true, message: '请选择开始日期' }]}
              >
                <Input type="date" placeholder="请选择开始日期" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="结束日期"
                name="endDate"
                rules={[{ required: true, message: '请选择结束日期' }]}
              >
                <Input type="date" placeholder="请选择结束日期" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="项目预算"
                name="budget"
                rules={[{ required: true, message: '请输入项目预算' }]}
              >
                <Input type="number" placeholder="请输入项目预算" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="承建单位"
                name="contractor"
                rules={[{ required: true, message: '请输入承建单位' }]}
              >
                <Input placeholder="请输入承建单位" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="项目描述"
            name="description"
            rules={[{ required: true, message: '请输入项目描述' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入项目详细描述" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginRight: '8px' }}>
              {editingProject ? '更新' : '添加'}
            </Button>
            <Button onClick={() => setIsModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 里程碑弹窗 */}
      <Modal
        title={`${selectedProject?.name} - 里程碑管理`}
        open={isMilestoneModalVisible}
        onCancel={() => setIsMilestoneModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedProject && (
          <div>
            <Card size="small" style={{ marginBottom: '16px' }}>
              <p><strong>项目名称：</strong>{selectedProject.name}</p>
              <p><strong>项目进度：</strong>{selectedProject.progress}%</p>
              <p><strong>项目状态：</strong>
                <Tag color={
                  selectedProject.status === 'planning' ? 'orange' :
                  selectedProject.status === 'in-progress' ? 'blue' :
                  selectedProject.status === 'completed' ? 'green' : 'red'
                }>
                  {selectedProject.status === 'planning' ? '规划中' :
                   selectedProject.status === 'in-progress' ? '进行中' :
                   selectedProject.status === 'completed' ? '已完成' : '延期'}
                </Tag>
              </p>
            </Card>
            
            <Timeline
              items={selectedProject.milestones.map(milestone => ({
                color: milestone.status === 'completed' ? 'green' : 
                       milestone.status === 'current' ? 'blue' : 'gray',
                children: (
                  <div>
                    <p style={{ margin: 0, fontWeight: 'bold' }}>{milestone.name}</p>
                    <p style={{ margin: '4px 0', color: '#666' }}>{milestone.date}</p>
                    <p style={{ margin: 0 }}>{milestone.description}</p>
                    <Tag color={milestone.status === 'completed' ? 'green' : 
                               milestone.status === 'current' ? 'blue' : 'orange'}>
                      {milestone.status === 'completed' ? '已完成' : 
                       milestone.status === 'current' ? '进行中' : '即将开始'}
                    </Tag>
                  </div>
                )
              }))}
            />
          </div>
        )}
      </Modal>
    </div>
  )
}

export default DigitalRuralConstructionManagement